from flask import session
from . import index_blue
from info import redis_store
from flask import render_template, current_app, request, jsonify
from info.models import User, News, Category
from info import constants, response_code


@index_blue.route('/news_list')
def index_news_list():
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=response_code.RET.PWDERR, errmsg='参数有误')


    if cid == 1:
        paginate = News.query.order_by(News.create_time.desc()).paginate(page, per_page, False)
    else:
        paginate = News.query.filter(News.category_id==cid).order_by(News.create_time.desc()).paginate(page, per_page, False)

    news_list = paginate.items

    total_page = paginate.pages

    current_page = paginate.page

    news_dict_List = []
    for news in news_list:
        news_dict_List.append(news.to_basic_dict())


    data = {
        'news_dict_List':news_dict_List,
        'total_page':total_page,
        'current_page':current_page
    }


    return jsonify(errno=response_code.RET.OK, errmsg='OK', data=data)






# @index_blue.route('/news_list')
# def index_news_list():
#     """提供主页新闻列表数据
#     1.接受参数（新闻分类id,当前第几页，每页多少条）
#     2.校验参数（判断以上参数是否是数字）
#     3.根据参数查询用户需要的数据:根据新闻发布时间倒叙，最后时限分页
#     4.构造响应的新闻数据
#     5.响应新闻数据
#     """
#     # 1.接受参数（新闻分类id,当前第几页，每页多少条）
#     cid = request.args.get('cid', '1')
#     page = request.args.get('page', '1')
#     per_page = request.args.get('per_page', '10')
#
#     # 2.校验参数（判断以上参数是否是数字）
#     try:
#         cid = int(cid)
#

@index_blue.route('/')
def index():
    """主页"""
    user_id = session.get('user_id', None)
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    news_clicks = []
    try:
        news_clicks = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)


    context = {
        'user':user.to_dict() if user else None,
        'news_clicks':news_clicks,
        'categories':categories
    }


    return render_template('news/index.html', context = context)

@index_blue.route("/favicon.ico", methods=["GET"])
def favicon():

    # 'test2/info/static/news/favicon.ico'
    return current_app.send_static_file("news/favicon.ico")